# -*- coding: utf-8 -*-
from accost.shortcuts import *
from chee.util import *
from chee.permission import *
############################################################################
__all__ = ['AuthHandler', 'JsonHandler','UserHandler','UserAjaxHandler','AdminHandler','AdminAjaxHandler']

class AuthHandler(Handler):
    def __call__(self, kwargs):
        initAuth(self.request)
        resp = super(AuthHandler, self).__call__(kwargs)
        setCookie(self.request,resp)
        return resp
class JsonHandler(Handler):
    def __call__(self, kwargs):
        from chee.models import User_Info
        uid = self.request.form.get('uid','').strip()
        uik = self.request.form.get('uik','').strip()
        if not uid or not uik: 
            return JsonMsg(False,u'error.login',u'不允许这样操作')
        if uid and uid.isdigit():
            usr_id = int(uid); 
            usr = store.find(User_Info,User_Info.id==usr_id).fetchOne(cache,'user_item_%d'%usr_id,3600)
            if not usr: return JsonMsg(False,u'error.login',u'没有这个用户')
            if usr and uik == usr.key:
                self.request.user_id = usr.id; self.request.user = usr;
        if not self.request.user:
            return JsonMsg(False,u'error.login',u'登陆超时, 您需要重新登录')
        resp = super(UserHandler, self).__call__(kwargs)
        return resp
class UserHandler(Handler):
    need_perms = []
    def __call__(self, kwargs):
        initAuth(self.request)
        if not self.request.user:
            return redirect('/login/?to=%s'%self.request.t_url)
        if not checkPermission(self):
            return ShowInfo(self.request,self.errors,u'您无权查看本页')
        resp = super(UserHandler, self).__call__(kwargs)
        setCookie(self.request,resp)
        return resp
class UserAjaxHandler(Handler):
    need_perms = []
    def __call__(self, kwargs):
        initAuth(self.request)
        if not self.request.user:
            return AjaxInfo(u'您需要先登录')
        if not checkPermission(self):
            return AjaxInfo(u'您无权做此操作')
        resp = super(UserAjaxHandler, self).__call__(kwargs)
        setCookie(self.request,resp)
        return resp
class AdminHandler(Handler):
    need_perms = []
    def __call__(self, kwargs):
        initAuth(self.request)
        if not self.request.user:
            return redirect('/login/?to=%s'%self.request.t_url)
        if self.request.perm_ids == None or len(self.request.perm_ids) == 0:
            return ShowInfo(self.request,self.errors,u'您无权查看本页')
        if not checkPermission(self):
            return AdminInfo(self.request,self.errors,u'您无权查看本页')
        resp = super(AdminHandler, self).__call__(kwargs)
        setCookie(self.request,resp)
        return resp
class AdminAjaxHandler(Handler):
    need_perms = []
    def __call__(self, kwargs):
        initAuth(self.request)
        if not self.request.user:
            return AjaxInfo(u'您需要先登录')
        if self.request.perm_ids == None or len(self.request.perm_ids) == 0:
            return ShowInfo(u'您无权做此操作')
        if not checkPermission(self):
            return AjaxInfo(u'您无权做此操作')
        resp = super(AdminAjaxHandler, self).__call__(kwargs)
        setCookie(self.request,resp)
        return resp
def setCookie(request,response,clear_specuser=True):
    if request.user:
        if (not request.cookies.has_key('uid') or not request.cookies.has_key('uik')
             or not request.cookies['uid'].isdigit() or request.cookies['uid'] != str(request.user_id)):
            response.set_cookie('uid',str(request.user_id))
            response.set_cookie('uik',request.user.key)
    else:
        response.delete_cookie('uid')
        response.delete_cookie('uik')
        if not request.cookies.has_key('referer'):
            if hasattr(request,'referer') and request.referer: response.set_cookie('referer',request.referer)
def initAuth(request):
    setNonAuthInfo(request)
    from chee.models import User_Info
    ## 先检测oooxm用户是否发生了改变
    result = setUserForIvCookie(request)
    if not result: setNoUser(request)
    setPerm(request)
def setUserForIvCookie(request):
    from chee.models import User_Info
    if request.cookies.has_key('uid') and request.cookies.has_key('uik'):# chee cookie
        # 查看是否有cookie
        usr_idstr = request.cookies['uid']; uik = request.cookies['uik']
        if usr_idstr and usr_idstr.isdigit():
            usr_id = int(usr_idstr); 
            usr = store.find(User_Info,User_Info.id==usr_id).fetchOne(cache,'user_item_%d'%usr_id,3600)
            if not usr: return False
            if usr and uik == usr.key:
                setUserInfo(request,usr)
                return True
    return False
def setUserInfo(request,usr):
    request.user_id = usr.id; request.user = usr;
    request.perm_ids = request.user.getPerm_ids()
def setNoUser(request):
    # if cookie not have referer, set, or else, ignore
    if not request.cookies.has_key('referer'):
        if request.headers.has_key('Referer'): 
            ref = request.headers['Referer']
            import urlparse
            ref_urlp = urlparse.urlparse(ref)
            if request.headers['host'] != ref_urlp.hostname: request.referer = ref
    request.user_type = -1
    request.user_id = None
    request.user = None
    request.perm_ids = None
def setPerm(request):
    perm = permission()
    perm.assign_perm_ids(request.perm_ids)
    request.perm_const = perm
def setNonAuthInfo(request):
    u = GlobalUtils()
    request.utils = u
    from chee.fileHelper import FileHelper
    request.pathHelper = FileHelper()
    import urlparse
    now_urlp = urlparse.urlparse(request.url)
    request.t_url = request.url
    request.net_loc = now_urlp.netloc
    if request.t_url.find(request.host) < 0: request.t_url = 'http://%s%s'%(request.host,request.t_url)
    request.r_url = urllib.quote(request.t_url)
    
def checkPermission(this_handler):
    # check permission
    if len(this_handler.need_perms) > 0:
        perm = this_handler.request.perm_const
        if not perm.check_perm_list(this_handler.need_perms):
            # still not, so deny this request
            return False
        else:
            return True
    else:
        return True

